package ge.telasi.tasks.ui.task;

import ge.telasi.tasks.model.Task;
import ge.telasi.tasks.model.TaskReceiverIndex;
import ge.telasi.tasks.ui.comp.CommonDialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 * @author dimitri
 */
public class TaskSelectorDialog extends CommonDialog {
    private TaskSearchPanel searchPanel;
    private JButton btnSelect;
    private JButton btnClose;
    private boolean approved = false;

    public TaskSelectorDialog(Component parent) {
        super(parent, true);
        initComponents();
    }

    @Override
    public void setVisible(boolean visible) {
        if (visible) {
            approved = false;
        }
        super.setVisible(visible);
    }

    private void initComponents() {
        setTitle("აარჩიეთ დავალება");
        setSize(800, 400);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(createCentralComponent(), BorderLayout.CENTER);
        getContentPane().add(createBottomComponent(), BorderLayout.SOUTH);
        getRootPane().setDefaultButton(btnSelect);
    }

    private Component createCentralComponent() {
        searchPanel = new TaskSearchPanel();
        return searchPanel;
    }

    private Component createBottomComponent() {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        btnSelect = new JButton("არჩევა");
        btnClose = new JButton("დახურვა");
        btnSelect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (searchPanel.getSelection() != null) {
                    approved = true;
                    setVisible(false);
                }
            }
        });
        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                approved = false;
                setVisible(false);
            }
        });
        panel.add(btnSelect, BorderLayout.EAST);
        panel.add(btnClose, BorderLayout.WEST);
        return panel;
    }

    public boolean isApproved() {
        return approved;
    }

    public List<Task> getSelections() {
        List<TaskReceiverIndex> indecies = searchPanel.getSelections();
        List<Task> tasks = new ArrayList<Task>();
        if (indecies != null) {
            for (TaskReceiverIndex index : indecies) {
                tasks.add(index.getTask());
            }
        }
        return tasks;
    }

}
